﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Web;

namespace StandardInterface
{
    public class GetRequestinfo
    {
        // 模拟缓存服务
        private static readonly Dictionary<string, string> SYSTEM_CACHE = new Dictionary<string, string>();

        // ecology 系统发放的授权许可证(appid)
        private static readonly string APPID = "EEAA5436-7577-4BE0-8C6C-89E9D44801EA";

        private static readonly HttpClient httpClient = new HttpClient();

        public static async Task Test()
        {
            string reqeustids = "1304197";
            string userids = "23844";

            string[] requestid = reqeustids.Split(',');
            string[] userid = userids.Split(',');

            for (int i = 0; i < requestid.Length; i++)
            {
                Console.WriteLine(requestid[i] + "   " + userid[i]);
                string param = "requestId=" + requestid[i];
                await TestRestful("http://oa.maxwell-gp.com.cn:8090", "/api/workflow/paService/getWorkflowRequest", param, userid[i]);
            }
        }

        public static async Task Main(string[] args)
        {
            await Test();
        }

        /// <summary>
        /// 第一步：调用 ecology 注册接口,根据 appid 进行注册,将返回服务端公钥和 Secret 信息
        /// </summary>
        public static async Task<Dictionary<string, object>> TestGetoken(string address)
        {
            // 从系统缓存或者数据库中获取 ECOLOGY 系统公钥和 Secret 信息
            string secret = "6a393956-42c1-4b75-8b77-91c342ed90f1";
            string spk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmIqeh3HlAxMNSjepuY1YsRj6pqfX/r88v1xOKI7+vIXDpMLgmaA8ytRGTyHaxscXiXxcCKE6T+z54qrxaxw6b4/WSfcH8QaghHhQRAtvMWxP/SC1Vg5dniQMUVvrsB2wbf0DfyiftGeBf8gJbe1uWsXrMZLZE3olrDMCjylo8SwIDAQAB";

            SYSTEM_CACHE["SERVER_PUBLIC_KEY"] = spk;
            SYSTEM_CACHE["SERVER_SECRET"] = secret;

            // 对秘钥进行加密传输，防止篡改数据
            string encryptSecret = RSAEncrypt(secret, spk);

            // 调用 ECOLOGY 系统接口进行注册
            var request = new HttpRequestMessage(HttpMethod.Post, address + "/api/ec/dev/auth/applytoken");
            request.Headers.Add("appid", APPID);
            request.Headers.Add("secret", encryptSecret);
            request.Headers.Add("time", "3600");

            var response = await httpClient.SendAsync(request);
            string data = await response.Content.ReadAsStringAsync();

            Console.WriteLine("TestGetoken()：" + data);

            var datas = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);

            // ECOLOGY 返回的 token
            string token = datas.ContainsKey("token") ? datas["token"]?.ToString() ?? "" : "";
            SYSTEM_CACHE["SERVER_TOKEN"] = token;

            return datas;
        }

        public static async Task<string> TestRestful(string address, string api, string queryParams, string userid)
        {
            try
            {
                // ECOLOGY 返回的 token
                var tokenData = await TestGetoken(address);
                string token = tokenData.ContainsKey("token") ? tokenData["token"]?.ToString() ?? "" : "";
                string spk = SYSTEM_CACHE.ContainsKey("SERVER_PUBLIC_KEY") ? SYSTEM_CACHE["SERVER_PUBLIC_KEY"] : "";

                // 对用户信息进行加密传输
                string encryptUserid = RSAEncrypt(userid, spk);

                // 构建完整的URL（将查询参数附加到URL）
                string fullUrl = address + api + "?" + queryParams;

                Console.WriteLine($"请求URL: {fullUrl}");
                Console.WriteLine($"请求参数: {queryParams}");

                // 调用 ECOLOGY 系统接口 - 使用GET方法并将参数放在URL中
                var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);
                request.Headers.Add("appid", APPID);
                request.Headers.Add("token", token);
                request.Headers.Add("userid", encryptUserid);

                var response = await httpClient.SendAsync(request);
                string data = await response.Content.ReadAsStringAsync();

                Console.WriteLine("token:" + token);
                Console.WriteLine("加密后的userid:" + encryptUserid);
                Console.WriteLine("TestRestful()响应：" + data);

                // 解析响应查看详细信息
                try
                {
                    var responseObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(data);
                    if (responseObj.ContainsKey("code") && responseObj["code"]?.ToString() != "0")
                    {
                        Console.WriteLine("错误代码: " + responseObj["code"]);
                        if (responseObj.ContainsKey("errMsg"))
                        {
                            Console.WriteLine("错误信息: " + JsonConvert.SerializeObject(responseObj["errMsg"]));
                        }
                    }
                }
                catch (Exception jsonEx)
                {
                    Console.WriteLine("解析响应JSON时出错: " + jsonEx.Message);
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("TestRestful执行失败: " + ex.Message);
                return "{\"code\":\"ERROR\",\"errMsg\":\"" + ex.Message + "\"}";
            }
        }

        /// <summary>
        /// 使用RSA公钥加密数据（支持X.509格式公钥）
        /// </summary>
        static string RSAEncrypt(string data, string publicKey)
        {
            try
            {
                // 将Base64公钥转换为字节数组
                byte[] publicKeyBytes = Convert.FromBase64String(publicKey);

                using (RSA rsa = RSA.Create())
                {
                    // 导入X.509格式的公钥
                    rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);

                    // 加密数据，使用PKCS#1填充
                    byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                    byte[] encryptedBytes = rsa.Encrypt(dataBytes, RSAEncryptionPadding.Pkcs1);

                    return Convert.ToBase64String(encryptedBytes);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"RSA加密失败: {ex.Message}");
                Console.WriteLine($"StackTrace: {ex.StackTrace}");
                return null;
            }
        }
    }
}